/**
 * Created by kinghackers on 2016/11/29.
 */
var formidable = require('formidable');
var fs = require('fs');
var upload = {};
upload.config = {
    uploadDir: 'public/upload/formidable/' //注意，此目录一定要真实存在
};

upload.upload = function (req, config, callback) {
    var result = {flag : true};
    var form = new formidable.IncomingForm({
        encoding:"utf-8",
        uploadDir: upload.config.uploadDir,  //文件上传地址
        keepExtensions:true,  //保留后缀
        // hash:'md5',
        multiples:false
    });
    form.parse(req, function(err, fields, files) {
        if(err){
            callback(err);
            return;
        }
        if(files.file_data.size <= 0){
            callback(err, "不允许上传空文件！");
            return;
        }
        console.log(files);
        //audio/mp3   text/plain  application/octet-stream  video/avi  video/mp4  application/msword
        var type = files.file_data.type.split("/")[0];
        // console.info(type);
        var type_url = "";
        if("image" == type){ //图片
            type_url = "image/";
        }else if("audio" == type){ //音频
            type_url = "audio/";
        }else if("video" == type){ //视频
            type_url = "video/";
        }else{ //其他文件
            type_url = "file/";
        }
        var path = upload.config.uploadDir + type_url + new Date().getTime() + "_" + files.file_data.name;
        fs.renameSync(files.file_data.path, path);  //重命名
        result.path = path;
        result.name = files.file_data.name;
        result.size = files.file_data.size;
        callback(err, result);
    });
};

upload.delete = function (req, callback) {
    var result = {flag : true};
    var path = __dirname + "/../public/" + req.body.key;
    // console.info("删除的路径：" + path);
    fs.exists(path, function(exists) {
        if(exists){
            fs.unlinkSync(path); // 删除
        }
        callback(result);
    });
};

module.exports = upload;